package com.beiding.oa2;

import java.util.*;

public class ObjectSet {

    private Map<Integer, Object> objects = new HashMap<>();

    private Collection<AnalyzeObject> analyzeObjects;

    public List<AnalyzeObject> getByType(Class type) {
        List<AnalyzeObject> r = new ArrayList<>();

        for (AnalyzeObject analyzeObject : analyzeObjects) {
            if (analyzeObject.about(type)) {
                r.add(analyzeObject);
            }
        }
        return r;
    }

    //不会检查类型的兼容性问题
    public void changeType(Class from, Class to) {
        if (analyzeObjects == null) {
            throw new RuntimeException("先使用scan方法进行扫描");
        }

        List<AnalyzeObject> byType = getByType(from);

        //首先切换新类型
        for (AnalyzeObject object : byType) {
            object.newType(to);
        }

        //执行构建
        for (AnalyzeObject object : byType) {
            object.build();
        }

        //对象切换
        for (AnalyzeObject object : byType) {
            object.shift();
        }

    }

    public void add(Object object) {
        objects.put(System.identityHashCode(object), object);
    }

    public void remove(Object object) {
        objects.remove(System.identityHashCode(object));
    }

    public void scan() {
        Object[] objects = this.objects.values().toArray();
        this.analyzeObjects = AnalyzeUtils.scan(objects);
    }

}
